package com.prj.ufdm.demo.tutorial.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.springframework.stereotype.Service;

@Service("testSocketServer")
public class TestSocketServer {
	
	//服务器端口号
	public static final int SERVER_PORT = 9999;

	/***
	 * 启动服务器
	 * @param 服务器监听的端口号，服务器ip无需指定，系统自动分配
	 */
	public void startSocketServer() {
		
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(SERVER_PORT);
			System.out.println("\n socket 9999 服务已启动。。。");
			Executor executor = Executors.newFixedThreadPool(100);
			while (true) {
				Socket socketClient = serverSocket.accept();
				executor.execute(new ThreadHandle(socketClient));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public class ThreadHandle implements Runnable {
		Socket socket = null;
		public ThreadHandle(Socket socket) {
			this.socket = socket;
		}
		public void run() {
			try {
				System.out.println("\n 接收到请求.......");
				String receiveMess = new String(readStream(socket.getInputStream()),"UTF-8");
				System.out.println("\n 接收到信息:" + receiveMess);
				socket.shutdownInput();
				String responseMess = "MESSAGE--" + receiveMess + "--RECEIVED";
				OutputStream ops = socket.getOutputStream();
				ops.write(responseMess.getBytes());
				ops.flush();
				System.out.println("\n 通知信息:" + responseMess);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static byte[] readStream(InputStream inStream) throws Exception {
		int count = 0;
		while (count == 0) {
			count = inStream.available();
		}
		byte[] b = new byte[count];
		inStream.read(b);
		return b;
	}
}
